package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.mapper.AdminMapper;
import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.service.IAdminService;
import com.csdj.server.utils.AdminUtil;
import com.csdj.server.utils.JwtTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZouLi
 * @since 2022-12-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    /**
     * 注入userDetailsService
     **/
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 注入passwordEncoder 密码加密
     **/
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 注入JwtUtil token工具类
     **/
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 请求头信息
     **/
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 注入mapper
     **/
    @Autowired(required = false)
    private AdminMapper adminMapper;

    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        // 获取验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isBlank(code) || !captcha.equals(code)){
            return RespBean.error("验证码错误！");
        }

        // 根据用户名加载用户
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 如果用户为null 或者 前端的密码跟获取到的用户的密码不一致
        if (null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码错误！");
        }
        // 判断账号是否启用
        if (!userDetails.isEnabled()){
            return RespBean.error("账号已被禁用！请联系管理员。");
        }

        // 用户授权
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 将用户授权信息存储到 security上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        // 存储token信息
        Map<String,Object> tokenMap = new HashMap<String,Object>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功！",tokenMap);
    }

    @Override
    public Admin getUserByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
    }

    @Override
    public List<Admin> getAllAdmin(String keyword) {
        return adminMapper.getAllAdmin(AdminUtil.getCurrentAdmin().getId(), keyword);
    }

    @Override
    public RespBean updatePassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        if (passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(pass));
            if (adminMapper.updateById(admin)>0) {
                return RespBean.success("修改成功！");
            }
        }
        return RespBean.error("修改失败！");
    }

    /**
     * @Description: 更新用户头像信息
     * @Param [url, id, authentication]
     * @Return com.csdj.server.pojo.RespBean
     * @Throws
     **/
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        // 修改
        int res = adminMapper.updateById(admin);
        if (1 == res){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            // 更新Authentication
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, authentication.getCredentials(), authentication.getAuthorities()));
            return RespBean.success("更新成功！",url);
        }
        return RespBean.error("更新失败！");
    }
}
